package com.agileai.portal.controller.schedule;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.schedule.DailyScheduleManage;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;

public class DailyScheduleDataProviderHandler extends BaseHandler {
	
	public ViewRenderer prepareDisplay(DataParam param){
		String year = param.get("year");
		String month = param.get("month");
		String userCode = param.get("userCode");
		
		DailyScheduleManage dailyScheduleManage = this.lookupService(DailyScheduleManage.class);
		String sdate = year + "-" + month + "-01";
		Date tempDate = DateUtil.getEndOfMonth(DateUtil.getDate(sdate));
		String edate = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, tempDate);
		
		DataParam queryParam = new DataParam("userCode",userCode,"sDate",sdate,"eDate",edate);
		List<DataRow> records = dailyScheduleManage.findRecords(queryParam);
		JSONObject jsonObject = new JSONObject();
		List<String> dates = new ArrayList<String>();
		for (int i=0;i < records.size();i++){
			DataRow row = records.get(i);
			Timestamp date = row.getTimestamp("SCHEDULE_TIME");
			Date dateTemp = new Date(date.getTime());
			String lightDate = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, dateTemp).substring(8,10);
			String parsedDate = String.valueOf(Integer.parseInt(lightDate));
			if (!dates.contains(parsedDate)){
				dates.add(parsedDate);
			}
		}
		try {
			String lightDays = StringUtil.append(dates.toArray(new String[0]),",");
			jsonObject.put("lightDays", lightDays);			
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
//		this.setAttribute("result", jsonObject.toString());
//		return new LocalRenderer(getPage());
		return new AjaxRenderer(jsonObject.toString());
	}
}